@file:Suppress("ktlint")

package io.hellsinger.vortex.data.repository

import io.hellsinger.filesystem.attribute.EmptyPathAttribute
import io.hellsinger.vortex.data.model.OperationState
import io.hellsinger.vortex.data.model.PathItem
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.count
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.test.runTest
import org.junit.Test

class StorageOperationStateProducerTest {

    private val producer = mockk<StorageOperationStateProducer>()

    @Test
    fun state_mapper() = runTest {

        val max = 1000

        every { producer.getState() } returns flow {
            repeat(max) { progress ->
                emit(
                    OperationState.Transition(
                        id = progress,
                        type = COPY,
                        source = PathItem(path = "/source/file${progress}.txt", EmptyPathAttribute),
                        progress = progress + 1L,
                        max = max.toLong(),
                        dest = PathItem(path = "/dest", EmptyPathAttribute),
                    )
                )
                delay(1000L)
            }
        }


        val count = producer.getState()
            .map { state ->
                state.createMessage()
            }.onEach { message ->
                println(message)
            }.count()
        assert(count == max)
    }

    fun OperationState.createMessage(): String =
        when (type) {
            COPY -> {
                val transition = this as OperationState.Transition
                val dest = transition.dest
                val source = transition.source
                "${source.path.getNameAt()} copied to ${dest.path.getNameAt()}"
            }

            else -> throw IllegalArgumentException("Unsupported type ($type)")
        }

    companion object {
        const val COPY = 1 shl 4
    }
}
